using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using Quiki.ExpressionParsers;
using Wintellect.PowerCollections;

namespace Quiki
{
    public class WikiDocument
    {
        public WikiDocument(WikiDocReference documentName, string fileName)
        {
            this.reference = documentName;
            this.fileName = fileName;
        }

        public string Body
        {
            get { return body; }
            set { body = value; }
        }

        public WikiDocReference Reference
        {
            get { return reference; }
        }

        public string FileName
        {
            get { return fileName; }
        }

        public Set<string> Categories
        {
            get { return categories; }
        }

        public string PathToRoot
        {
            get
            {
                string path = Path.GetDirectoryName(FileName);
                StringBuilder pathToRoot = new StringBuilder();

                while (false == String.IsNullOrEmpty(path))
                {
                    pathToRoot.Append("../");
                    path = Path.GetDirectoryName(path);
                }

                return pathToRoot.ToString();
            }
        }

        public string Title
        {
            get
            {
                if (title != null)
                    return title;
 
                return Reference.LastPart.Replace('_', ' ');
            }

            set
            {
                title = value;
            }
        }

        [SuppressMessage ("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
        public DateTime GenerationTime { get { return DateTime.Now; } }

        public WikiTextElement RootElement
        {
            get { return rootElement; }
            set { rootElement = value; }
        }

        public string ConstructFileName (string rootDirectory, string fileExtension)
        {
            StringBuilder outputDirName = new StringBuilder(rootDirectory);

            foreach (string part in Reference.Parts)
            {
                if (outputDirName.Length > 0)
                    outputDirName.Append(Path.DirectorySeparatorChar);
                outputDirName.Append(part.Replace(' ', '_'));
            }

            outputDirName.Append(fileExtension);
            return outputDirName.ToString();
        }

        public void SetCustomTitle (string title)
        {
            this.title = title;
        }

        private string body;
        private Set<string> categories = new Set<string>();
        private readonly string fileName;
        private readonly WikiDocReference reference;
        private WikiTextElement rootElement;
        private string title;
    }
}